'use client';

import { useState, useEffect } from 'react';
import Image from 'next/image';
import { fetchBooks, saveBookNote } from '../actions/books';
import type { BookNote } from '../types';
import { useRouter } from 'next/navigation';
type Tab = 'Technical' | 'Novel' | 'Non-tech Learning';

export default function BookNotes() {
  const router = useRouter();
  const [activeTab, setActiveTab] = useState<Tab>('Technical');
  const [books, setBooks] = useState<BookNote[]>([]);
  const [loading, setLoading] = useState(true);
  const [editingBook, setEditingBook] = useState<string | null>(null);
  const [editingNote, setEditingNote] = useState('');

  useEffect(() => {
    const loadBooks = async () => {
      setLoading(true);
      try {
        const data = await fetchBooks(activeTab);
        setBooks(data);
      } catch (error) {
        console.error('Failed to fetch books:', error);
        // Add error handling UI here
      } finally {
        setLoading(false);
      }
    };

    loadBooks();
  }, [activeTab]);

  const handleNoteEdit = (bookId: string, currentNote: string) => {
    setEditingBook(bookId);
    setEditingNote(currentNote);
  };

  const handleNoteSave = async (bookId: string) => {
    try {
      await saveBookNote(bookId, editingNote);
      setBooks(books.map(book => 
        book.id === bookId ? { ...book, note: editingNote } : book
      ));
      setEditingBook(null);
    } catch (error) {
      console.error('Failed to save note:', error);
      // Add error handling UI here
    }
  };

  const handleBookClick = (bookId: string) => {
    router.push(`/book-notes/${bookId}`);
  };

  return (
    <div className="min-h-screen p-8">
      {/* Header Card */}
      <div className="bg-slate-800 text-white p-6 rounded-lg mb-8 max-w-md ml-auto">
        <h1 className="text-[#FF9851] text-3xl font-bold mb-4">Reading List</h1>
        <p className="text-gray-300">Here are books notes shared by me!</p>
      </div>

      {/* Tabs */}
      <div className="flex gap-4 mb-8">
        {['Technical', 'Novel', 'Non-tech Learning'].map((tab) => (
          <button
            key={tab}
            onClick={() => setActiveTab(tab as Tab)}
            className={`px-4 py-2 rounded-md transition-colors ${
              activeTab === tab
                ? 'text-[#FF9851] border-b-2 border-[#FF9851]'
                : 'text-gray-500 hover:text-gray-700'
            }`}
          >
            {tab}
          </button>
        ))}
      </div>

      {/* Loading State */}
      {loading && (
        <div className="flex justify-center items-center h-64">
          <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-[#FF9851]"></div>
        </div>
      )}

      {/* Book Grid */}
      {!loading && (
        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6">
          {books.map((book) => (
            <div
              key={book.id}
              className="bg-white rounded-lg p-6 shadow-lg hover:shadow-xl transition-shadow cursor-pointer"
              onClick={() => handleBookClick(book.id)}
            >
              <Image
                src={book.image}
                alt={book.title}
                width={300}
                height={400}
                className="w-full h-auto object-cover mb-4"
              />
              <h3 className="font-semibold text-lg mb-2">{book.title}</h3>
              
              {editingBook === book.id ? (
                <div className="mt-4">
                  <textarea
                    value={editingNote}
                    onChange={(e) => setEditingNote(e.target.value)}
                    className="w-full p-2 border rounded-md"
                    rows={4}
                  />
                  <div className="flex justify-end gap-2 mt-2">
                    <button
                      onClick={(e) => {
                        e.stopPropagation();
                        setEditingBook(null);
                      }}
                      className="px-3 py-1 text-sm text-gray-600 hover:text-gray-800"
                    >
                      Cancel
                    </button>
                    <button
                      onClick={(e) => {
                        e.stopPropagation();
                        handleNoteSave(book.id);
                      }}
                      className="px-3 py-1 text-sm bg-[#FF9851] text-white rounded-md hover:bg-[#FFB07F]"
                    >
                      Save
                    </button>
                  </div>
                </div>
              ) : (
                <div 
                  onClick={(e) => {
                    e.stopPropagation();
                    handleNoteEdit(book.id, book.note);
                  }}
                  className="mt-4 p-2 bg-gray-50 rounded-md cursor-pointer hover:bg-gray-100"
                  dangerouslySetInnerHTML={{ __html: book.note || 'Click to add notes...' }}
                />
              )}
            </div>
          ))}
        </div>
      )}
    </div>
  );
}